import {
	baseUrl,
	appKey
} from "@/src/utils/envir.js"

//  统一的拦截方法
export const fetch = (url, opt) => {
	let params = opt.data || {}
	let method = opt.method || 'GET'
	let paths = (method == 'GET' && Object.keys(params).length > 0) ? ('?' + Object.keys(params).map(key => key + '=' +
		params[key]).join('&')) : ''
	let urls = baseUrl + url + paths
	// token 放到 header 中
	let header = {}
	let token = uni.getStorageSync('token')
	if (token) {
		header = {
			Authorization: token
		}
	}
	//  合并对象
	header = {
		...opt.header,
		...header
	}

	console.log('👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇🏻');
	console.log("-- 请求地址: ", urls);
	console.log("-- 请求方式: ", method);
	console.log("-- 请求参数: " + JSON.stringify(params));
	// console.log("-- 请求header: ",header);

	return new Promise((resolve, reject) => {
		uni.request({
			url: urls,
			data: params,
			method: method,
			header: header,
			success: (res) => {
				console.log("-- 打印请求数据: " + JSON.stringify(res));
				console.log('👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆🏻');
				console.log('---  AAAAAAAAAAAA');
				interceptorsRes(res, resolve, reject)
			},
			fail: (err) => {
				// reject(err)
				interceptorsErr(err, reject)
			}
		})
	})
}

//  响应拦截
const interceptorsRes = (res, resolve, reject) => {
	const code = res.statusCode
	if (code === 200) {
		console.log('-- 请求成功');
	} else if (code === 401) {
		console.log("-- 未授权，跳转回登录页")
	} else {
		uni.showToast({
			icon: 'none',
			title: res.errMsg || '数据请求失败'
		})
	}
	resolve(res)
}

// 异常处理
const interceptorsErr = (error, reject) => {
	uni.showToast({
		icon: 'none',
		title: '网络异常,请稍后再试'
	}, 3000)
	reject(error)
}